package com.chenqincheng.tracing;

import java.util.List;

/**
 * @author 陈钦成
 *  Date: 2018/5/12 2:10
 *  description: byte数组和字符串互转工具类
 */
public class ByteStringUtils {
    /**
     * 数组转字符串
     * @param data byte数组
     * @param offset 起点
     * @param num 长度
     * @return 字符串
     */
    public static String byteArray2String(byte[] data, int offset, int num) {
        String in = "";
        for (int i = 0; i < num; i++) {
            byte loop = data[offset + i];
            String hex = Integer.toHexString(loop & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            in += hex;
        }
        return in;
    }

    /**
     * 16进制字符串转byte数组
     * @param message 16进制字符串
     * @return 字符串
     */
    public static byte[] string2ByteArray(String message) {
        byte[] b = new byte[message.length() / 2];
        int j = 0;

        for (int i = 0; i < b.length; i++) {
            char c0 = message.charAt(j++);
            char c1 = message.charAt(j++);

            b[i] = (byte) ((parse(c0) << 4) | parse(c1));
        }
        return b;
    }

    private static int parse(char c){
        if (c >= 'a') {
            return ((c - 'a' + 10) & 0x0f);
        }
        if (c >= 'A') {
            return ((c - 'A' + 10) & 0x0f);
        }
        return ((c - '0') & 0x0f);
    }

    private byte[] hexStrToByteArray(String str)
    {
        if (str == null) {
            return null;
        }
        if (str.length() == 0) {
            return new byte[0];
        }
        byte[] byteArray = new byte[str.length() / 2];
        for (int i = 0; i < byteArray.length; i++){
            String subStr = str.substring(2 * i, 2 * i + 2);
            byteArray[i] = ((byte)Integer.parseInt(subStr, 16));
        }
        return byteArray;
    }

    /**
     * 获取数据长度
     * @param list list字符串数据
     * @return 数据长度
     */
    public static int getDataLength(List<String> list) {
        if (list == null) {
            return 0;
        }
        int length = 0;
        for (String item : list) {
            length += item.length();
        }
        return length / 2;
    }

    /**
     * 校验和 Check Sum：从PREFIX ~ DATA 所有数据的算术和的最低2字节
     * @param bytes 数据
     * @return 校验字符串
     */
    public static String CKS(byte[] bytes){
        long chsByte = 0;
        for(int i = 0; i < bytes.length; i++){
            chsByte += (bytes[i] & 0xFF);
        }
        byte[] chsByteArray = {(byte) ((chsByte>>8) & 0xFF), (byte) ((chsByte) & 0xFF)};
        return byteArray2String(chsByteArray,0,chsByteArray.length);
    }


}
